<template>
  <div :style="{margin: '0 auto',width:'100%'}">
    <el-row :gutter="60" class="main">
      <el-form ref="formRef" :model="dataForm" :rules="dataRule" size="medium" label-width="100px" label-position="top"
               :disabled="setting.readonly">
        <template v-if="!loading && formOperates">
          <!-- 具体表单 -->
          <el-col :span="4">
            <el-row :gutter="60">
              <el-col :span="24">
                <jnpf-form-tip-item>
                  <JnpfText
                    :textStyle='{"color":"#000000","font-weight":"normal","text-decoration":"none","font-size":12,"line-height":32,"font-style":"normal","text-align":"left"}'>
                  </JnpfText>
                </jnpf-form-tip-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="16" class="demand-main">
            <el-row :gutter="60">
              <el-col :span="24">
                <jnpf-form-tip-item>
                  <JnpfText
                    :textStyle='{"color":"#1684FC","font-weight":"bold","text-decoration":"none","font-size":24,"line-height":32,"font-style":"normal","text-align":"center"}'
                    content="企业需求">
                  </JnpfText>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('demandProductName')">
                <jnpf-form-tip-item
                  label="需求产品名称" v-if="judgeShow('demandProductName')" prop="demandProductName">
                  <JnpfInput v-model="dataForm.demandProductName" @change="changeData('demandProductName',-1)"
                             placeholder="请输入" :disabled="judgeWrite('demandProductName')" clearable
                             :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('county')">
                <jnpf-form-tip-item
                  label="区县" v-if="judgeShow('county')" prop="county">
                  <JnpfInput v-model="dataForm.county" @change="changeData('county',-1)"
                             placeholder="请输入" :disabled="judgeWrite('county')" readonly clearable
                             :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('enterpriseName')">
                <jnpf-form-tip-item
                  label="企业名称" v-if="judgeShow('enterpriseName')" prop="enterpriseName">
                  <JnpfInput v-model="dataForm.enterpriseName" @change="changeData('enterpriseName',-1)"
                             placeholder="请输入" :disabled="judgeWrite('enterpriseName')" readonly clearable
                             :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('enterpriseCreditCode')">
                <jnpf-form-tip-item
                  label="企业信用代码" v-if="judgeShow('enterpriseCreditCode')" prop="enterpriseCreditCode">
                  <JnpfInput v-model="dataForm.enterpriseCreditCode" @change="changeData('enterpriseCreditCode',-1)"
                             placeholder="请输入" :disabled="judgeWrite('enterpriseCreditCode')" readonly clearable
                             :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('industry')">
                <jnpf-form-tip-item
                  label="所属行业" v-if="judgeShow('industry')" prop="industry">
                  <JnpfInput v-model="dataForm.industry" @change="changeData('industry',-1)"
                             placeholder="请输入" :disabled="judgeWrite('industry')" readonly clearable
                             :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('specificIndustry')">
                <jnpf-form-tip-item
                  label="细分行业" v-if="judgeShow('specificIndustry')" prop="specificIndustry">
                  <JnpfInput v-model="dataForm.specificIndustry" @change="changeData('specificIndustry',-1)"
                             placeholder="请输入" :disabled="judgeWrite('specificIndustry')" readonly clearable
                             :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="judgeShow('isLoan')">
                <jnpf-form-tip-item
                  label="是否有贷款意向" tipLabel="该选项需申请项目后自动带入" v-if="judgeShow('isLoan')" prop="isLoan">
                  <JnpfRadio v-model="dataForm.isLoan" @change="changeData('isLoan',-1)"
                             :disabled="judgeWrite('isLoan')" optionType="default" direction="horizontal" size="small"
                             :options="isLoanOptions" :props="isLoanProps">
                  </JnpfRadio>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('demandType')">
                <jnpf-form-tip-item
                  label="需求类型" v-if="judgeShow('demandType')" prop="demandType">
                  <JnpfCascader v-model="dataForm.demandType" @change="changeData('demandType',-1)"
                                placeholder="请选择" show-all-levels :disabled="judgeWrite('demandType')" clearable
                                :style='{"width":"100%"}' separator="/" :options="demandTypeOptions"
                                :props="demandTypeProps">
                  </JnpfCascader>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('procureNum')">
                <jnpf-form-tip-item
                  label="数量及单位" v-if="judgeShow('procureNum')" prop="procureNum">
                  <JnpfInput v-model="dataForm.procureNum" @change="changeData('procureNum',-1)"
                             placeholder="请输入" :disabled="judgeWrite('procureNum')" clearable :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('procureBudget')">
                <jnpf-form-tip-item
                  label="需求预算总价（万元）" v-if="judgeShow('procureBudget')" prop="procureBudget">
                  <JnpfInputNumber v-model="dataForm.procureBudget" @change="changeData('procureBudget',-1)"
                                   placeholder="请输入" :disabled="judgeWrite('procureBudget')" addonAfter="万元" :step="1"
                                   :controls="false">
                  </JnpfInputNumber>
                </jnpf-form-tip-item>
              </el-col>

              <el-col :span="12" v-if="judgeShow('endDate')">
                <jnpf-form-tip-item
                  label="需求截止日期" v-if="judgeShow('endDate')" prop="endDate">
                  <JnpfDatePicker v-model="dataForm.endDate" @change="changeData('endDate',-1)"
                                  :startTime="dateTime(false,1,1,'','')" :endTime="dateTime(false,1,1,'','')"
                                  placeholder="请选择" :disabled="judgeWrite('endDate')" clearable
                                  :style='{"width":"100%"}' type="date" format="yyyy-MM-dd">
                  </JnpfDatePicker>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="judgeShow('demandDes')">
                <jnpf-form-tip-item
                  label="需求详细说明" v-if="judgeShow('demandDes')" prop="demandDes">
                  <JnpfTextarea v-model="dataForm.demandDes" @change="changeData('demandDes',-1)"
                                placeholder="请输入" :disabled="judgeWrite('demandDes')" :style='{"width":"100%"}' true
                                type="textarea" :autosize='{"minRows":4,"maxRows":4}'>
                  </JnpfTextarea>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('demandContacts')">
                <jnpf-form-tip-item
                  label="需求联系人" v-if="judgeShow('demandContacts')" prop="demandContacts">
                  <JnpfInput v-model="dataForm.demandContacts" @change="changeData('demandContacts',-1)"
                             placeholder="请输入" :disabled="judgeWrite('demandContacts')" clearable
                             :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('phone')">
                <jnpf-form-tip-item
                  label="联系电话" v-if="judgeShow('phone')" prop="phone">
                  <JnpfInput v-model="dataForm.phone" @change="changeData('phone',-1)"
                             placeholder="请输入" :disabled="judgeWrite('phone')" clearable :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="judgeShow('adress')">
                <jnpf-form-tip-item
                  label="需求联系地址" v-if="judgeShow('adress')" prop="adress">
                  <JnpfInput v-model="dataForm.adress" @change="changeData('adress',-1)"
                             placeholder="请输入" :disabled="judgeWrite('adress')" clearable :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="judgeShow('files')">
                <jnpf-form-tip-item
                  label="其他材料说明" v-if="judgeShow('files')" prop="files">
                  <JnpfUploadFile v-model="dataForm.files" @change="changeData('files',-1)"
                                  :disabled="judgeWrite('files')" :fileSize="10" sizeUnit="MB" :limit="9"
                                  pathType="defaultPath" :isAccount="0" buttonText="点击上传">
                  </JnpfUploadFile>
                </jnpf-form-tip-item>
              </el-col>
              <!--              <el-col :span="12" v-if="judgeShow('isurgent')">
                              <jnpf-form-tip-item
                                label="是否加急" v-if="judgeShow('isurgent')" prop="isurgent">
                                <JnpfSelect v-model="dataForm.isurgent" @change="changeData('isurgent',-1)"
                                            placeholder="请选择" :disabled="judgeWrite('isurgent')" clearable :style='{"width":"100%"}'
                                            :options="isurgentOptions" :props="isurgentProps">
                                </JnpfSelect>
                              </jnpf-form-tip-item>
                            </el-col>
                            <el-col :span="12" v-if="judgeShow('mateStatus')">
                              <jnpf-form-tip-item
                                label="智能匹配状态" v-if="judgeShow('mateStatus')" prop="mateStatus">
                                <JnpfSelect v-model="dataForm.mateStatus" @change="changeData('mateStatus',-1)"
                                            placeholder="请选择" :disabled="judgeWrite('mateStatus')" clearable :style='{"width":"100%"}'
                                            :options="mateStatusOptions" :props="mateStatusProps">
                                </JnpfSelect>
                              </jnpf-form-tip-item>
                            </el-col>-->
            </el-row>
          </el-col>
          <el-col :span="4">
            <el-row :gutter="60">
              <el-col :span="24">
                <jnpf-form-tip-item>
                  <JnpfText
                    :textStyle='{"color":"#000000","font-weight":"normal","text-decoration":"none","font-size":12,"line-height":32,"font-style":"normal","text-align":"left"}'>
                  </JnpfText>
                </jnpf-form-tip-item>
              </el-col>
            </el-row>
          </el-col>
          <!-- 表单结束 -->
        </template>
        <SelectDialog v-if="selectDialogVisible" :config="currTableConf" :formData="dataForm"
                      ref="selectDialog" @select="addForSelect" @close="selectDialogVisible=false"/>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit"/>
  </div>
</template>

<script>
import request from '@/utils/request'
import {mapGetters} from "vuex";
import {getFormById} from '@/api/workFlow/FormDesign'
import comMixin from '@/views/workFlow/workFlowForm/mixin';
import {getDataInterfaceRes} from '@/api/systemData/dataInterface'
import {getDictionaryDataSelector} from '@/api/systemData/dictionary'
import {getDefaultCurrentValueUserId} from '@/api/permission/user'
import {getDefaultCurrentValueDepartmentId} from '@/api/permission/organize'
import {
  getDateDay,
  getLaterData,
  getBeforeData,
  getBeforeTime,
  getLaterTime
} from '@/components/Generator/utils/index.js'
import {thousandsFormat} from "@/components/Generator/utils/index"
import axios from "axios";

export default {
  mixins: [comMixin],
  components: {},
  props: [],
  data() {
    return {
      dataFormSubmitType: 0,
      continueBtnLoading: false,
      index: 0,
      prevDis: false,
      nextDis: false,
      allList: [],
      visible: false,
      loading: false,
      btnLoading: false,
      formRef: 'formRef',
      setting: {},
      eventType: '',
      userBoxVisible: false,
      selectDialogVisible: false,
      currTableConf: {},
      dataValueAll: {},
      addTableConf: {},
      //可选范围默认值
      ableAll: {},
      tableRows: {},
      Vmodel: "",
      currVmodel: "",
      dataForm: {
        demandProductName: undefined,
        county: undefined,
        enterpriseName: undefined,
        enterpriseCreditCode: undefined,
        industry: undefined,
        specificIndustry: undefined,
        demandType: [],
        procureNum: undefined,
        procureBudget: undefined,
        endDate: undefined,
        demandDes: undefined,
        demandContacts: undefined,
        phone: undefined,
        adress: undefined,
        files: [],
        isurgent: '否',
        mateStatus: '未匹配',
        creatoruserid: undefined,
        creatortime: undefined,
        lastmodifyuserid: undefined,
        lastmodifytime: undefined,
        isLoan: undefined,
      },
      tableRequiredData: {},
      dataRule:
        {
          demandProductName: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          county: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          enterpriseName: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          enterpriseCreditCode: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          industry: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          specificIndustry: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          demandType: [
            {
              required: true,
              message: '请至少选择一个',
              trigger: 'change'
            },
          ],
          procureNum: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          procureBudget: [
            {
              required: true,
              message: '请输入',
              trigger: ["blur", "change"]
            },
          ],
          endDate: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],
          demandDes: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          demandContacts: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          phone: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
        },
      demandTypeOptions: [],
      demandTypeProps: {"label": "fullName", "value": "id", "children": "children"},
      isurgentOptions: [{"fullName": "是", "id": "是"}, {"fullName": "否", "id": "否"}],
      isurgentProps: {"label": "fullName", "value": "id"},
      mateStatusOptions: [{"fullName": "成功", "id": "成功"}, {"fullName": "失败", "id": "失败"}, {
        "fullName": "未匹配",
        "id": "未匹配"
      }],
      isLoanOptions: [{"fullName": "是", "id": "1"}, {"fullName": "否", "id": "0"}],
      isLoanProps: {"label": "fullName", "value": "id"},
      mateStatusProps: {"label": "fullName", "value": "id"},
      childIndex: -1,
      isEdit: false,
      interfaceRes: {
        demandProductName: [],
        county: [],
        enterpriseName: [],
        enterpriseCreditCode: [],
        industry: [],
        specificIndustry: [],
        isLoan: [],
        demandType: [],
        procureNum: [],
        procureBudget: [],
        endDate: [],
        demandDes: [],
        demandContacts: [],
        phone: [],
        adress: [],
        files: [],
        isurgent: [],
        mateStatus: [],
        creatoruserid: [],
        creatortime: [],
        lastmodifyuserid: [],
        lastmodifytime: [],
      },
    }
  },
  computed: {
    formOperates() {
      return this.setting.formOperates
    },
    ...mapGetters(['userInfo']),
  },
  watch: {},
  created() {
    this.selectProjectIsLoan();
    this.selectUserInfo();
    this.getFormById()
    if (this.dataForm.id == null || this.dataForm.id == '' && this.dataForm.id == undefined || this.dataForm.id == 0) {
      this.initDefaultData()
    }
    this.dataValueAll = JSON.parse(JSON.stringify(this.dataForm))
  },
  mounted() {
  },
  methods: {
    selectProjectIsLoan(){
      const userId = this.userInfo.userAccount;
      const url = `http://test-fzzxqy.demo-caii.com/cloud-api2/fzzxqy/select_project_info?userId=${userId}`;
      axios.get(url).then(res => {
        const projectInfo = res.data.data[0]
        this.dataForm.isLoan = projectInfo.F_Is_Loan
      })
    },
    selectUserInfo() {
      const userId = this.userInfo.userAccount;
      const url = `http://test-fzzxqy.demo-caii.com/cloud-api2/fzzxqy/company_base_main?userId=${userId}`;
      axios.get(url).then(res => {
        const companyInfo = res.data.data[0]
        this.dataForm.enterpriseName = companyInfo.Enterprise_name;
        this.dataForm.enterpriseCreditCode = companyInfo.Enterprise_credit_code;
        this.dataForm.county = companyInfo.Owning_region;
        this.dataForm.industry = companyInfo.industry;
        this.dataForm.specificIndustry = companyInfo.Specific_industry;
      })
    },
    changeData(model, index) {
      this.isEdit = false
      this.childIndex = index
      let modelAll = model.split("-");
      let faceMode = "";
      for (let i = 0; i < modelAll.length; i++) {
        faceMode += modelAll[i];
      }
      for (let key in this.interfaceRes) {
        if (key != faceMode) {
          let faceReList = this.interfaceRes[key]
          for (let i = 0; i < faceReList.length; i++) {
            if (faceReList[i].relationField == model) {
              let options = 'get' + key + 'Options';
              if (this[options]) {
                this[options]()
              }
              this.changeData(key, index)
            }
          }
        }
      }
    },
    changeDataFormData(type, data, model, index, defaultValue) {
      if (!this.isEdit) {
        if (type == 2) {
          for (let i = 0; i < this.dataForm[data].length; i++) {
            if (index == -1) {
              this.dataForm[data][i][model] = defaultValue
            } else if (index == i) {
              this.dataForm[data][i][model] = defaultValue
            }
          }
        } else {
          this.dataForm[data] = defaultValue
        }
      }
    },
    dataAll() {
      this.getdemandTypeOptions();
    },
    selfGetInfo(dataForm) {
      this.dataInfo(dataForm)
    },
    beforeSubmit() {
      const _data = this.dataList()
      return _data
    },
    selfInit() {
      this.dataAll()
    },
    getFormById() {
      getFormById("539808336179102853").then(res => {
        this.dataForm.flowId = res.data && res.data.flowId
        // this.encode = res.data&&res.data.encode
      })
    },
    exist() {
      let isOk = true
      for (let key in this.tableRequiredData) {
        if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
          for (let i = 0; i < this.dataForm[key].length; i++) {
            let item = this.dataForm[key][i]
            inner: for (let id in item) {
              let arr = this.tableRequiredData[key].filter(o => o.id === id) || []
              if (!arr.length) continue inner
              if (arr[0].required) {
                let msg = `${arr[0].name}不能为空`
                let boo = true
                if (arr[0].dataType === 'array') {
                  boo = !this.jnpf.isEmptyArray(item[id])
                } else {
                  boo = !this.jnpf.isEmpty(item[id])
                }
                if (!boo) {
                  this.$message({
                    message: msg,
                    type: 'error',
                    duration: 1000
                  })
                  isOk = false
                  break
                }
              }
            }
          }
        }
      }
      return isOk
    },
    getdemandTypeOptions() {
      getDictionaryDataSelector('539790426240974917').then(res => {
        this.demandTypeOptions = res.data.list
      })
    },
    goBack() {
      this.$emit('refresh')
    },
    clearData() {
      this.dataForm = JSON.parse(JSON.stringify(this.dataValueAll))
    },
    //初始化默认数据
    initDefaultData() {

    },
    openSelectDialog(key) {
      this.currTableConf = this.addTableConf[key]
      this.currVmodel = key
      this.selectDialogVisible = true
      this.$nextTick(() => {
        this.$refs.selectDialog.init()
      })
    },
    addForSelect(data) {
      for (let i = 0; i < data.length; i++) {
        let t = data[i]
        if (this['get' + this.currVmodel]) {
          this['get' + this.currVmodel](t)
        }
      }
    },
    dateTime(timeRule, timeType, timeTarget, timeValueData, dataValue) {
      let timeDataValue = null;
      let timeValue = Number(timeValueData)
      if (timeRule) {
        if (timeType == 1) {
          timeDataValue = timeValue
        } else if (timeType == 2) {
          timeDataValue = dataValue
        } else if (timeType == 3) {
          timeDataValue = new Date().getTime()
        } else if (timeType == 4) {
          let previousDate = '';
          if (timeTarget == 1 || timeTarget == 2) {
            previousDate = getDateDay(timeTarget, timeType, timeValue)
            timeDataValue = new Date(previousDate).getTime()
          } else if (timeTarget == 3) {
            previousDate = getBeforeData(timeValue)
            timeDataValue = new Date(previousDate).getTime()
          } else {
            timeDataValue = getBeforeTime(timeTarget, timeValue).getTime()
          }
        } else if (timeType == 5) {
          let previousDate = '';
          if (timeTarget == 1 || timeTarget == 2) {
            previousDate = getDateDay(timeTarget, timeType, timeValue)
            timeDataValue = new Date(previousDate).getTime()
          } else if (timeTarget == 3) {
            previousDate = getLaterData(timeValue)
            timeDataValue = new Date(previousDate).getTime()
          } else {
            timeDataValue = getLaterTime(timeTarget, timeValue).getTime()
          }
        }
      }
      return timeDataValue;
    },
    time(timeRule, timeType, timeTarget, timeValue, formatType, dataValue) {
      let format = formatType == 'HH:mm' ? 'HH:mm:00' : formatType
      let timeDataValue = null
      if (timeRule) {
        if (timeType == 1) {
          timeDataValue = timeValue || '00:00:00'
          if (timeDataValue.split(':').length == 3) {
            timeDataValue = timeDataValue
          } else {
            timeDataValue = timeDataValue + ':00'
          }
        } else if (timeType == 2) {
          timeDataValue = dataValue
        } else if (timeType == 3) {
          timeDataValue = this.jnpf.toDate(new Date(), format)
        } else if (timeType == 4) {
          let previousDate = '';
          previousDate = getBeforeTime(timeTarget, timeValue)
          timeDataValue = this.jnpf.toDate(previousDate, format)
        } else if (timeType == 5) {
          let previousDate = '';
          previousDate = getLaterTime(timeTarget, timeValue)
          timeDataValue = this.jnpf.toDate(previousDate, format)
        }
      }
      return timeDataValue;
    },
    dataList() {
      var _data = this.dataForm;
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll
      this.dataForm = _dataAll
      this.isEdit = true
      this.dataAll()
      this.childIndex = -1
    },
  },
}

</script>
<style lang="scss" scoped>
.main .demand-main {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1) !important;
  border: 1px solid #EBEEF5;
  padding: 20px;
  border-radius: 5px;

  .print-button {
    position: absolute;
    top: 0;
    right: 0;
  }
}

::v-deep .el-textarea__inner {
  min-height: 100px !important;
}

::v-deep .el-input-number--medium {
  width: 100% !important;
}
</style>
